﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.DirectX;
using EdytorWF.Objects;
using Microsoft.DirectX.Direct3D;

namespace EdytorWF.Engine
{
    public class BoundingBox
    {
        public Vector3 B1 { get; set; } // the smallest values X,Y,Z
        public Vector3 B2 { get; set; } //the largest value of X,Y,Z
        public Vector3 Origin { get; set; }

        public BoundingBox()
        {
            B1 = new Vector3(0, 0, 0);
            B2 = new Vector3(0, 0, 0);
            Origin = new Vector3(0, 0, 0);
        }

        public BoundingBox(Vector3 _b1, Vector3 _b2)
        {
            B1 = _b1;
            B2 = _b2;
            ComputeOrigin();
        }

        public BoundingBox(ModelObject mo)
        {
            List<CustomVertex.PositionNormalTextured> tmp_vec = mo.GetVertices();
            float min_x = float.MaxValue, max_x = float.MinValue;
            float min_y = float.MaxValue, max_y = float.MinValue;
            float min_z = float.MaxValue, max_z = float.MinValue;

            for (int i = 0; i < tmp_vec.Count; ++i)
            {
                if (tmp_vec[i].X < min_x)
                    min_x = tmp_vec[i].X;
                if (tmp_vec[i].X > max_x)
                    max_x = tmp_vec[i].X;

                if (tmp_vec[i].Y < min_y)
                    min_y = tmp_vec[i].Y;
                if (tmp_vec[i].Y > max_y)
                    max_y = tmp_vec[i].Y;

                if (tmp_vec[i].Z < min_z)
                    min_z = tmp_vec[i].Z;
                if (tmp_vec[i].Z > max_z)
                    max_z = tmp_vec[i].Z;
            }

            B1 = new Vector3(min_x, min_y, min_z);
            B2 = new Vector3(max_x, max_y, max_z);
            ComputeOrigin();
        }

        public void ComputeOrigin()
        {
            float tmp_X = B1.X + (B2.X - B1.X) / 2;
            float tmp_Y = B1.Y + (B2.Y - B1.Y) / 2;
            float tmp_z = B1.Z + (B2.Z - B1.Z) / 2;
            Origin = new Vector3(tmp_X, tmp_Y, tmp_z);
        }
    }
}
